//
//  TradeRecordsViewController.m
//  阿帕
//
//  Created by mac on 2020/1/2.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "NoticeMessageViewController.h"
#import "NoticeMsgCell.h"
#import "HuoYuanDetailViewController.h"
#import "YunDanCenterTabbar.h"
#import "YunDanCenterDetailViewController.h"
#import "CarTeamAuthVC.h"
#import "DriverAuthVC.h"
#import "VehicleListViewController.h"

@interface NoticeMessageViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (nonatomic, assign) NSInteger pageNum;

@end

static NSString *const cellID = @"NoticeCellID";

static const CGFloat cellHeight = 150;

@implementation NoticeMessageViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self setupBaseView];
    
    [self requestNoticeRecords];
    //    [self noticeRecordsListRequest];
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"消息通知";
    
    self.view.backgroundColor = BackgroundColor;
    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [resetButton setTitle:@"全部已读" forState:UIControlStateNormal];
    resetButton.titleLabel.font = font(14);
    [resetButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(rightBarItemClick) forControlEvents:UIControlEventTouchUpInside];
        
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:resetButton];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.view addSubview:self.tableView];
    
    if (self.dataArray.count == 0) {
        self.foundImageView.hidden = NO;
        self.tableView.hidden = YES;
    }
}

//- (void)noticeRecordsListRequest {
//
//    WEAKSELF
//    if (_pageNum == 1) {
//        [self.dataArray removeAllObjects];
//    }
//
//    NSDictionary *params = @{
//        @"pageNum": [NSNumber numberWithInteger:_pageNum],
//        @"pageSize": DEFULT_LOAD_NUM,
//        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
//    };
//
//    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], NOTICERECORD) withParameter:params withVC:self netName:@"消息通知" success:^(id response, NSString *msg) {
//
//        if ([response[@"records"] count] != 0) {
//
//            [weakSelf.dataArray addObjectsFromArray:[NoticeModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
//            [weakSelf.tableView.mj_header endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshing];
//
//        }else{
//            if (_pageNum == 1) {
//                weakSelf.foundImageView.hidden = NO;
//                weakSelf.tableView.hidden = YES;
//            }
//
//            [weakSelf.tableView.mj_header endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
//
//        }
//
//        [weakSelf.tableView reloadData];
//
//    } failure:^(NSInteger code, NSString *msg) {
//
//    }];
//}

- (void)requestNoticeRecords {
    WEAKSELF
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = @{
        @"pageNum": [NSNumber numberWithInteger:_pageNum],
        @"pageSize": DEFULT_LOAD_NUM,
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], JPUSHMESSAGE) withParameter:params withVC:self netName:@"消息通知" success:^(id response, NSString *msg) {
        if ([response[@"records"] count] != 0) {
            NSArray *records = response[@"records"];
            for (NSDictionary *record in records) {
                NoticeModel *noticeModel = [NoticeModel mj_objectWithKeyValues:record];
                [weakSelf.dataArray addObject:noticeModel];
            }
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

/// 设置消息已读
/// @param noticeCode 消息的code
- (void)setReadedWithNoticeCode:(NSString *)noticeCode {
    NSDictionary *params = @{@"code": noticeCode};
    [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], JPUSHMESSAGE) withParameter:params withVC:self netName:@"设置消息已读" success:^(id response, NSString *msg) {
        [KNotificationCenter postNotificationName:REFRESHHOMENOTICECOUNT object:nil];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self requestNoticeRecords];
}

- (void)loadMoreData{
    _pageNum ++;
    [self requestNoticeRecords];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];
//    cell.dataDic = self.dataArray[indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    return cellHeight;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NoticeModel *model = self.dataArray[indexPath.row];
    if ([model.havaRead isEqualToString:@"0"]) {
        [self setReadedWithNoticeCode:model.code];
        model.havaRead = @"1";
        [tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
    }
    if ([model.extras.isSystem isEqualToString:@"1"]) {
        [XSInfoView showInfo:@"系统消息，无法查看详情" onView:self.view];
    } else {
        if ([model.extras.type isEqual: NOTICE_HUOYUANDETAIL]) {
            // 货源详情
            NSInteger codeLength = [model.extras.params length];
            NSString *orderCode = [model.extras.params substringWithRange:NSMakeRange(5, codeLength - 5)];
            
            HuoYuanDetailViewController *hydvc = [[HuoYuanDetailViewController alloc] init];
            hydvc.orderCode = orderCode;
            hydvc.massageCode = model.code;
            [self.navigationController pushViewController:hydvc animated:YES];
            
        } else if ([model.extras.type isEqual: NOTICE_YUNDANDETAIL]) {
            // 运单详情
            NSInteger codeLength = [model.extras.params length];
            NSString *orderCode = [model.extras.params substringWithRange:NSMakeRange(5, codeLength - 5)];
            YunDanCenterDetailViewController *ydcdvc = [[YunDanCenterDetailViewController alloc] init];
            ydcdvc.orderCode = orderCode;
            [self.navigationController pushViewController:ydcdvc animated:YES];
            
        } else if ([model.extras.type isEqual: NOTICE_YUNDANLIST_CANCEL]) {
            // 运单列表 已取消状态
            YunDanCenterTabbar *ydctb = [[YunDanCenterTabbar alloc] init];
            ydctb.selectedIndex = 6;
            [self.navigationController pushViewController:ydctb animated:YES];
            
        } else if ([model.extras.type isEqual: NOTICE_YUNDANLIST_ALL]) {
            // 运单列表 全部状态
            YunDanCenterTabbar *ydctb = [[YunDanCenterTabbar alloc] init];
            ydctb.selectedIndex = 0;
            [self.navigationController pushViewController:ydctb animated:YES];
        } else if ([model.extras.type isEqual: NOTICE_AUTH_BAN]) {
            if (Identity_CarCaptain) {
                CarTeamAuthVC *ctavc = [[CarTeamAuthVC alloc] init];
                [self.navigationController pushViewController:ctavc animated:YES];
            } else {
                DriverAuthVC *davc = [[DriverAuthVC alloc] init];
                davc.isNotEdit = CarCaptain_Driver ? YES : NO;
                [self.navigationController pushViewController:davc animated:YES];
            }
        } else if ([model.extras.type isEqual: NOTICE_AUTH_BAN_TEMA_CAR]) {

            VehicleListViewController *vlvc = [[VehicleListViewController alloc] init];
            vlvc.isCanBindVehicle = 0;
            [self.navigationController pushViewController:vlvc animated:YES];
            
        }
    }
}


#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 10, ScreenW, ScreenH - NavHeight - MenuBarHeight - 10);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NoticeMsgCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.cy_centerX = self.view.cy_centerX;
        _foundImageView.cy_centerY = self.view.cy_centerY;
        _foundImageView.cy_centerY -= 80;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}
- (void)rightBarItemClick{
    [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], REDMESSAGE) withParameter:nil withVC:self netName:@"一键已读" success:^(id response, NSString *msg) {
        self.pageNum = 1;
        [self requestNoticeRecords];
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
}

@end
